import re

import requests
from lxml import etree
from bs4 import BeautifulSoup


def tranlate(keyword):
    character = {
        'n.': '[名]',
        'pron.': '[代]',
        'adj.': '[形]',
        'v.': '[动]',
        'adv.': '[副]',
        'num.': '[数]',
        'art.': '[冠]',
        'prep.': '[介]',
        'conj.': '[连]',
        'interj.': '[感叹]',
    }
    url = f'https://cn.bing.com/dict/search?q={keyword}&go=%E6%90%9C%E7%B4%A2&qs=ds&form=Z9LH5'
    response = requests.get(url,timeout=5)
    html = response.text
    etr = etree.HTML(html)
    soup = BeautifulSoup(html, 'lxml')
    content = etr.xpath('//div[@class="qdef"]/ul//text()')
    end_words = soup.find('div', attrs={'class': 'hd_if'})
    # print()
    if end_words is None:
        result = '；'.join(content)
    else:
        result = '；'.join(content) + end_words.text
    # 待匹配的词性
    pattern = 'n\.|pron\.|adj\.|v\.|adv\.|num\.|art\.|prep\.|conj\.|interj\.'
    items = re.findall(pattern, result)
    # 通过遍历将词性表示译为中文
    for item in items:
        result = result.replace(item, character[item])
    # print(result)
    response.close()
    return result


if __name__ == '__main__':
    keyword = input('输入要翻译的词汇：')
    result = tranlate(keyword)
    print(result)
